package com.example.bluetooth2;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.UUID;
import java.util.regex.Pattern;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.text.InputFilter;
import android.text.Spanned;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {
	SharedPreferences sPref;
	String text4save;
	public class myfilter implements InputFilter {
		
		
		@Override
		public CharSequence filter(CharSequence source, int start, int end,
				Spanned dest, int dstart, int dend) {
			
			    String pattern = getPattern();

			   

			    if (!Pattern.matches(pattern, source)) {

			      return "";

			    }
			return null;
		}
		 private String getPattern() {

			   String pattern = "[0-9a-fA-F]";  

			    return pattern;

			  }

	}
	private byte CalculateCheckSum( byte[] bytes ){
        short CheckSum = 0, i = 0;
        for( i = 0; i < bytes.length; i++){
             CheckSum += (short)(bytes[i] & 0xFF);
        }
        return (byte) CheckSum;
        //Log.i("Checksum", Integer.toHexString(CheckSum));
   }
	private static final String TAG = "bluetooth2";
	    
	  Button btnOn, btnOff;
	  TextView txtArduino,readbyte;
	  Handler h;
	  EditText commandhex;
	 
	  
	 
	  private static final int REQUEST_ENABLE_BT = 1;
	  final int RECIEVE_MESSAGE = 1;        // Статус для Handler
	  private BluetoothAdapter btAdapter = null;
	  private BluetoothSocket btSocket = null;
	  private StringBuilder sb = new StringBuilder();
	   
	  private ConnectedThread mConnectedThread;
	    
	  // SPP UUID сервиса
	  private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
	  
	  // MAC-адрес Bluetooth модуля
	  private static String address = "30:14:12:18:22:58";
	  /** Called when the activity is first created. */
	  @Override
	  public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    LoadText();
	    setContentView(R.layout.activity_main);
	  
	    btnOn = (Button) findViewById(R.id.btnOn);                  // кнопка включения
	    // btnOff = (Button) findViewById(R.id.btnOff);                // кнопка выключения
	   txtArduino = (TextView) findViewById(R.id.txtArduino);      // для вывода текста, полученного от Arduino
	   readbyte = (TextView) findViewById(R.id.ReadByte);      // для вывода текста, полученного от Arduino
	   commandhex = (EditText)findViewById(R.id.editText1);
	   commandhex.setText(text4save);
	   commandhex.setFilters(new InputFilter[] {new myfilter()});
	 
	   
	   h = new Handler() {
	        public void handleMessage(android.os.Message msg) {
	            switch (msg.what) {
	            case RECIEVE_MESSAGE:                                                   // если приняли сообщение в Handler
	                byte[] readBuf = (byte[]) msg.obj;
	               // String strIncom = new String(readBuf, 0, msg.arg1);
	                 readbyte.setText("Recieved Byte:"+ byteArrayToHexString(readBuf));
/*	                sb.append(strIncom);                                                // формируем строку
	                int endOfLineIndex = sb.indexOf("\n");                            // определяем символы конца строки
	                if (endOfLineIndex > 0) {                                            // если встречаем конец строки,
	                    String sbprint = sb.substring(0, endOfLineIndex);               // то извлекаем строку
	                    sb.delete(0, sb.length());                                      // и очищаем sb
	                    txtArduino.setText("Ответ от Arduino: " + sbprint);             // обновляем TextView
	                    btnOff.setEnabled(true);
	                    btnOn.setEnabled(true);
	                }
	                */
	                Log.d(TAG, "...Строка:"+ sb.toString() +  "Байт:" + msg.arg1 + "...");
	                break;
	            }
	        };
	    };
	      
	    btAdapter = BluetoothAdapter.getDefaultAdapter();       // получаем локальный Bluetooth адаптер
	    checkBTState();
	    btnOn.setOnClickListener(this);
		 
	         
	    
	  }
	    
	  @Override
	  public void onResume() {
	    super.onResume();
	 // Set up a pointer to the remote node using it's address.
	    BluetoothDevice device = btAdapter.getRemoteDevice(address);
	 	    
	    Method m = null;
		try {
			m = device.getClass().getMethod("createRfcommSocket",new Class[] { int.class });
		} catch (NoSuchMethodException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
        try {
        	btSocket = (BluetoothSocket) m.invoke(device,Integer.valueOf(1));
            Log.d(TAG, "...Соединяемся...");
            btSocket.connect();
            Log.d(TAG, device.getName() + " - connected");
        } catch (IOException e) {
            Log.e(TAG, "IOException: "+e.getLocalizedMessage());
            Log.d(TAG, device.getName() + " - not connected");
        } catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    
	      
	      // Discovery is resource intensive.  Make sure it isn't going on
	      // when you attempt to connect and pass your message.
	      btAdapter.cancelDiscovery();
	      
	     	      
	    // Create a data stream so we can talk to server.
	    Log.d(TAG, "...Создание Socket...");
	    
	    mConnectedThread = new ConnectedThread(btSocket);
	    mConnectedThread.start();
	    
	    		
	    		
	    		
	  }
	  
	  @Override
	  public void onPause() {
	    super.onPause();
	  
	    Log.d(TAG, "...In onPause()...");
	   
	    try     {
	      btSocket.close();
	    } catch (IOException e2) {
	      errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
	    }
	  }
	    
	  private void checkBTState() {
	    // Check for Bluetooth support and then check to make sure it is turned on
	    // Emulator doesn't support Bluetooth and will return null
	    if(btAdapter==null) {
	      errorExit("Fatal Error", "Bluetooth не поддерживается");
	    } else {
	      if (btAdapter.isEnabled()) {
	        Log.d(TAG, "...Bluetooth включен...");
	      } else {
	        //Prompt user to turn on Bluetooth
	        Intent enableBtIntent = new Intent(btAdapter.ACTION_REQUEST_ENABLE);
	        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
	      }
	    }
	  }
	 
 
	  private void errorExit(String title, String message){
	    Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
	    finish();
	  }
	  
	  private class ConnectedThread extends Thread {
	        private final BluetoothSocket mmSocket;
	        private final InputStream mmInStream;
	        private final OutputStream mmOutStream;
	      
	        public ConnectedThread(BluetoothSocket socket) {
	            mmSocket = socket;
	            InputStream tmpIn = null;
	            OutputStream tmpOut = null;
	      
	            // Get the input and output streams, using temp objects because
	            // member streams are final
	            try {
	                tmpIn = socket.getInputStream();
	                tmpOut = socket.getOutputStream();
	            } catch (IOException e) { }
	      
	            mmInStream = tmpIn;
	            mmOutStream = tmpOut;
	        }
	      
	        public void run() {
	            byte[] buffer = new byte[256];  // buffer store for the stream
	            int bytes; // bytes returned from read()
	 
	            // Keep listening to the InputStream until an exception occurs
	            while (true) {
	                try {
	                    // Read from the InputStream
	                    bytes = mmInStream.read(buffer);        // Получаем кол-во байт и само собщение в байтовый массив "buffer"
	                    h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget();     // Отправляем в очередь сообщений Handler
	                } catch (IOException e) {
	                    break;
	                }
	            }
	        }
	      
	        /* Call this from the main activity to send data to the remote device */
	        public void write(byte [] msg) {
	            Log.d(TAG, "...Данные для отправки: %x" + msg+ "...");
	            byte[] msgBuffer = msg;
	            try {
	                mmOutStream.write(msgBuffer);
	            } catch (IOException e) {
	                Log.d(TAG, "...Ошибка отправки данных: " + e.getMessage() + "...");    
	              }
	        }
	      
	        /* Call this from the main activity to shutdown the connection */
	        public void cancel() {
	            try {
	                mmSocket.close();
	            } catch (IOException e) { }
	        }
	    }
	@Override
	// определяем обработчик при нажатии на кнопку
    public void onClick(View v) {
  	
    //btnOn.setEnabled(false);
  	int command,hight,low;
  	
  	String a=commandhex.getText().toString();
  	if(a.length()==0)
  		a = text4save;
  	else 
  		text4save = a;
  	byte buff[] = new byte[a.length()];
   	buff=hexStringToByteArray(a);
  
   	
   txtArduino.setText(String.format("Send:%s", a));
   
   mConnectedThread.write(buff);    // Отправляем через Bluetooth команду из 4-х hex символов
  	
  	
     // Toast.makeText(getBaseContext(), "Сбрасываем гироскоп", Toast.LENGTH_SHORT).show();
    }
	public static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len/2];

        for(int i = 0; i < len; i+=2){
            data[i/2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i+1), 16));
        }

        return data;
    }
	public static String byteArrayToHexString(byte[] array) {
	    StringBuffer hexString = new StringBuffer();
	    for (byte b : array) {
	      int intVal = b & 0xff;
	      if (intVal < 0x10)
	        hexString.append("0");
	      hexString.append(Integer.toHexString(intVal));
	    }
	    return hexString.toString();    
	  }
	void LoadText()
	{
		sPref = getPreferences(MODE_PRIVATE);
		text4save = sPref.getString("commandhex", "");
		//Toast.makeText(this, "Text Load", Toast.LENGTH_LONG).show();
		
	}
	void SaveText()
	{
		sPref = getPreferences(MODE_PRIVATE);
		Editor ed = sPref.edit();
		ed.putString("commandhex", text4save.toString());
		ed.commit();
		//Toast.makeText(this, "Text Saved ", Toast.LENGTH_LONG).show();
	}
	protected void onDestroy(){
		SaveText();
		super.onDestroy();
	}
}
